<template>
  <div>
    <!-- 工具栏 -->
    <div>
      <el-row>
        <el-col :span="8">
          <!-- 操作按钮 -->
          <div class="operation-div">
            <el-button type="primary" @click="onAdd">添加</el-button>
          </div>
        </el-col>
        <el-col :span="16">
          <!-- 条件查询 -->
          <div class="search-div">
            <el-form :inline="true" :model="searchData" class="demo-form-inline">
              <el-form-item label="客户名称：">
                <el-input v-model="searchData.name" placeholder="请输入客户名" clearable />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="onSearch">查询</el-button>
                <el-button @click="onReset">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
      </el-row>
    </div>
    <!-- 表格内容 -->
    <div>
      <el-table :data="tableData" border stripe style="width: 100%" :header-cell-style="{ background: '#ECF5FF' }">
        <el-table-column type="index" :index="indexMethod" />
        <el-table-column prop="customerName" label="客户名称" />
        <el-table-column prop="address" label="客户地址" />
        <el-table-column prop="location" label="客户归属地" />
        <el-table-column prop="regionName" label="地区" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div style="margin-top: 20px">
        <el-pagination
          v-model:current-page="pageData.currentPage"
          v-model:page-size="pageData.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          background
          layout="->, jumper, total, sizes, prev, pager, next"
          :total="pageData.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 添加修改对话框表单-->
    <el-dialog v-model="dialogFormVisible" :title="title" width="500" draggable @close="onDialogFormCancel">
      <el-form :model="form" ref="ruleFormRef" :rules="rules">
        <el-form-item label="客户名称" prop="customerName">
          <el-input v-model="form.customerName" />
        </el-form-item>
        <el-form-item label="客户曾用名" prop="customerOldName">
          <el-input v-model="form.customerOldName" />
        </el-form-item>
        <el-form-item label="客户地址" prop="address">
          <el-input v-model="form.address" />
        </el-form-item>
        <el-form-item label="客户归属地" prop="location">
          <el-input v-model="form.location" />
        </el-form-item>
        <el-form-item label="地区" prop="regionName">
          <el-input v-model="form.regionName" />
        </el-form-item>
        <el-form-item label="客户联系人" prop="contact">
          <el-input v-model="form.contact" />
        </el-form-item>
        <el-form-item label="客户电话1" prop="phone1">
          <el-input v-model="form.phone1" />
        </el-form-item>
        <el-form-item label="客户电话2" prop="phone2">
          <el-input v-model="form.phone2" />
        </el-form-item>
        <el-form-item label="客户经理" prop="accountManager">
          <el-input v-model="form.accountManager" />
        </el-form-item>
        <el-form-item label="客户经理电话" prop="accountManagerPhone">
          <el-input v-model="form.accountManagerPhone" />
        </el-form-item>
        <el-form-item label="业务经理" prop="businessManager">
          <el-input v-model="form.businessManager" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="onDialogFormCancel">取消</el-button>
          <el-button type="primary" @click="onDialogFormConfirm">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  customerpageListService,
  customeraddUserService,
  customergetUserById,
  customerupdateUserService,
  customerdeleteByIdService
} from '@/api/user.js';

// 表单数据
const searchData = ref({
  name: ''
});

// 表格数据
const tableData = ref([]);

// 分页数据
const pageData = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 20
});
// 分页插件，每页条数发生改变时
const handleSizeChange = (val) => {
  pageData.pageSize = val;
  getPageList();
};

// 分页插件，当页码发生改变时
const handleCurrentChange = (val) => {
  pageData.currentPage = val;
  getPageList();
};

// 分页查询
const getPageList = async () => {
  const params = {
    currentPage: pageData.currentPage,
    pageSize: pageData.pageSize,
    name: searchData.value.name
  };
  const result = await customerpageListService(params);
  pageData.total = result.data.total;
  tableData.value = result.data.items;
};
getPageList();

// 头部表单函数定义
const onSearch = () => {
  getPageList();
};

// 重置查询表单
const onReset = () => {
  searchData.value = {};
  getPageList();
};

// 添加修改对话框表单
const form = ref({
  customerId: '',
  customerName: '',
  customerOldName: '',
  address: '',
  location: '',
  regionName: '',
  contact: '',
  phone1: '',
  phone2: '',
  accountManager: '',
  accountManagerPhone: '',
  businessManager: ''
});

// 重置对话框表单
const resetForm = () => {
  form.value = {
    customerId: '',
    customerName: '',
    customerOldName: '',
    address: '',
    location: '',
    regionName: '',
    contact: '',
    phone1: '',
    phone2: '',
    accountManager: '',
    accountManagerPhone: '',
    businessManager: ''
  };
  title.value = '添加用户';
  isAdd.value = true;
};

const title = ref('添加用户');
const isAdd = ref(true);
const dialogFormVisible = ref(false);

// 提交对话框表单按钮事件
const onDialogFormConfirm = async () => {
  if (!ruleFormRef.value) return;
  await ruleFormRef.value.validate((valid) => {
    if (valid) {
      confirm();
    }
  });
};

// 取消对话表单框按钮事件
const onDialogFormCancel = () => {
  dialogFormVisible.value = false;
  resetForm();
};

// 添加按钮事件
const onAdd = () => {
  title.value = '添加用户';
  isAdd.value = true;
  dialogFormVisible.value = true;
};

// 修改按钮事件
const handleEdit = async (index, row) => {
  title.value = '修改用户';
  isAdd.value = false;
  const id = { id: row.customerId };
  let result = await customergetUserById(id);
  form.value = result.data;
  dialogFormVisible.value = true;
};

// 删除按钮事件
const handleDelete = (index, row) => {
  ElMessageBox.confirm('确认要删除吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      let result = await customerdeleteByIdService(row.customerId);
      ElMessage.success(result.msg ? result.msg : '删除成功');
      getPageList();
    })
    .catch(() => {});
};

// 提交表单
const confirm = async () => {
  if (isAdd.value) {
    try {
      let result = await customeraddUserService(form.value);
      ElMessage.success(result.msg ? result.msg : '添加成功');
      dialogFormVisible.value = false;
      resetForm();
      getPageList();
    } catch (error) {
      console.error(error);
    }
  } else {
    try {
      let result = await customerupdateUserService(form.value);
      ElMessage.success(result.msg ? result.msg : '修改成功');
      dialogFormVisible.value = false;
      resetForm();
      getPageList();
    } catch (error) {
      console.error(error);
    }
  }
};

// 表单校验
const ruleFormRef = ref(null);
const rules = ref({
  customerName: [{ required: true, message: '客户名称不能为空', trigger: 'blur' }],
  address: [{ required: true, message: '客户地址不能为空', trigger: 'blur' }],
  location: [{ required: true, message: '客户归属地不能为空', trigger: 'blur' }],
  regionName: [{ required: true, message: '地区不能为空', trigger: 'blur' }]
});
</script>

<style scoped>
.operation-div {
  width: 100%;
  text-align: left;
  padding-left: 10px;
  padding-top: 10px;
}

.search-div {
  width: 100%;
  text-align: right;
  padding-top: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding: 10px 20px;
}
</style>
